package com.jd.platform.gobrs.client.dispatcher;

import com.jd.platform.gobrs.client.ApplicationContextProvider;
import com.jd.platform.gobrs.client.manager.AutoCacheManager;
import com.jd.platform.gobrs.client.manager.CacheManager;
import com.jd.platform.gobrs.client.manager.ManualCacheManager;
import com.jd.platform.gobrs.common.enums.CacheHandlerEnums;
import com.jd.platform.gobrs.common.exception.CacheHandlerNotFoundException;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: gobrs
 * @ClassName GCacheDispatcher
 * @description:
 * @author: sizegang
 * @create: 2022-01-08 22:40
 * @Version 1.0
 **/

public class GCacheDispatcher implements Dispatcher {

    private Map<Integer, CacheManager> targets = new ConcurrentHashMap<Integer, CacheManager>();

    @Resource
    private ApplicationContextProvider applicationContextProvider;


    @PostConstruct
    private void initCacheManager() {
        AutoCacheManager autoCacheManager = null;
        ManualCacheManager manualCacheManager = null;
        try {
            autoCacheManager = applicationContextProvider.getBean(AutoCacheManager.class);
            manualCacheManager = applicationContextProvider.getBean(ManualCacheManager.class);
        } catch (Exception ex) {
        } finally {
            if (manualCacheManager != null) {
                targets.put(CacheHandlerEnums.MANUAL_CACHE.getType(), manualCacheManager);
            }
            if (autoCacheManager != null) {
                targets.put(CacheHandlerEnums.AUTO_CACHE.getType(), autoCacheManager);
            }
        }
    }


    @Override
    public CacheManager doDispatch(Integer executor) {
        CacheManager cacheManager = targets.get(executor);
        if (cacheManager == null) {
            throw new CacheHandlerNotFoundException("not found this dispatcher cache manager!!!");
        }
        return cacheManager;
    }
}
